// pages/focus/focus.js
Page({

  /**
   * 页面的初始数据
   */
  data: {

    // 折叠面板
    activeNames: ['1'],

    // 今日专注列表
    todayFocusList: [],

    // 过往专注列表
    otherFocusList: [],

    // 是否展示倒计时面板
    isShowCountDownPanel: false,

    // 倒计时标题
    countDownTitle: "",
    // 倒计时标题输入框内容
    inputTitle: "",


    // 当前倒计时总时长
    countDownTimeTotal: 0,

    // 当前倒计时
    countDownTime: 0,

    // 倒计时场景 (专注 0，休息 1)
    countDownScene: 0,

    // 倒计时状态 (0:未开始, 1:正在进行, 2:暂停中, 3:已结束)
    countDownState: 0,

    // 倒计时定时器
    countDownTimer: null,

    // 日期选择器参数
    currentDate: '00:00',
    // 选择器时间
    timePickerTime: 0,
    minHour: 0,
    maxHour: 12,
    formatter(type, value) {
      if (type === 'hour') {
        return `${value}小时`;
      }
      if (type === 'minute') {
        return `${value}分钟`;
      }
      return value;
    },
    // 是否展示选择器弹框
    isShowTimePicker: false,

    // 是否展示输入标题框
    isShowTitleSheet: false,


    // 渐变色
    gradientColor1: {
      '0%': '#ffd01e',
      '100%': '#ee0a24',
    },
    gradientColor2: {
      '0%': '#59e0fd',
      '100%': '#538cfa',
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.queryAllFocus()
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    // 移除定时器
    if (this.countDownTimer != null) {
      clearInterval(this.countDownTimer)
    }
  },

  // 折叠面板change事件
  onChangeCollapse(event) {
    this.setData({
      activeNames: event.detail,
    });
  },

  // 展示倒计时面板
  showCountDownPanel() {
    this.setData({
      isShowCountDownPanel: !this.data.isShowCountDownPanel
    })
  },



  // 修改标题
  onChangeTitle(e) {
    this.setData({
      inputTitle: e.detail
    })
  },

  // 确定输入标题
  comfirmTitle() {
    this.setData({
      countDownTitle: this.data.inputTitle,
      isShowTitleSheet: false
    })
    if (this.data.countDownState == 0) {
      this.startCountDown()
    }
  },

  // 展示修改标题面板
  showTitleSheet() {
    this.setData({
      isShowTitleSheet: true
    })
  },

  // 关闭输入标题面板
  onCloseTitleSheet() {
    this.setData({
      isShowTitleSheet: false
    })
  },


  // 开始倒计时
  startCountDown() {
    let { countDownState, countDownTime, countDownTimeTotal, countDownTitle } = this.data

    if (countDownState == 1) {
      wx.showToast({
        title: '正在进行, 请勿重试',
        icon: 'none',
        duration: 1000
      })
      return
    }
    if (countDownTimeTotal == 0) {
      wx.showToast({
        title: '当前未设定时长',
        icon: 'none',
        duration: 1000
      })
      return
    }
    else if (countDownTitle.trim() == '') {
      this.setData({
        isShowTitleSheet: true
      })
      return
    }
    else if (countDownTime == 0) {
      wx.showToast({
        title: '当前专注已完成',
        icon: 'none',
        duration: 1000
      })
      return
    }
    this.setCountDownTimer()
  },

  // 暂停倒计时
  stopCountDown() {
    this.setData({
      countDownState: 2
    })
    clearInterval(this.data.countDownTimer)
  },

  // 重置倒计时
  resetCountDown() {
    wx.showModal({
      title: '提示',
      content: '是否要重置, 当前记录将不会保留',
      success: res => {
        if (res.confirm) {
          this.setData({
            countDownState: 0,
            countDownTime: 0,
            countDownTimeTotal: 0
          })
          clearInterval(this.data.countDownTimer)
        } else if (res.cancel) {
        }
      }
    })

  },

  // 结束计时
  endCountDown() {
    let { countDownTime, countDownTimeTotal, countDownState, countDownScene } = this.data
    if (countDownTimeTotal - countDownTime <= 30 && countDownTime != 0 && countDownScene == 0) {
      wx.showModal({
        title: '提示',
        content: '当前专注时长小于30秒, 此次专注将不会记录, 是否继续',
        success: res => {
          if (res.confirm) {
            clearInterval(this.data.countDownTimer)
            this.setData({
              countDownTime: 0,
              countDownTimeTotal: 0,
              countDownState: 0,
            })
          } else if (res.cancel) {
          }
        }
      })
    } else if (countDownTime > 0 && countDownState == 1 && countDownScene == 0) {
      wx.showModal({
        title: '提示',
        content: '是否要提前完成专注？',
        success: res => {
          if (res.confirm) {
            clearInterval(this.data.countDownTimer)
            // 添加记录
            this.addFocusItem(true)
            this.setData({
              countDownTime: 0,
              countDownTimeTotal: 0,
              countDownState: 0,
              countDownScene: 1
            })
          } else if (res.cancel) {
          }
        }
      })
    }
    else if (countDownTime == 0 && countDownState == 3 && countDownScene == 0) {
      // 添加记录
      this.addFocusItem()
      clearInterval(this.data.countDownTimer)
      this.setData({
        countDownTime: 0,
        countDownTimeTotal: 0,
        countDownState: 0,
        countDownScene: 1
      })
    }
    else if (countDownScene == 1 && countDownTime > 0) {
      wx.showModal({
        title: '提示',
        content: '是否提前结束休息',
        success: res => {
          if (res.confirm) {
            clearInterval(this.data.countDownTimer)
            this.setData({
              countDownTime: 0,
              countDownTimeTotal: 0,
              countDownState: 0,
              countDownScene: 0
            })
          } else if (res.cancel) {
          }
        }
      })
    }
    else if (countDownScene == 1 && countDownTime == 0) {
      wx.showToast({
        title: '休息结束!',
        icon: 'success',
        duration: 1000
      })
      clearInterval(this.data.countDownTimer)
      this.setData({
        countDownTime: 0,
        countDownTimeTotal: 0,
        countDownState: 0,
        countDownScene: 0
      })
    }



  },

  // 设置倒计时定时器
  setCountDownTimer() {
    let { countDownState, countDownTime, countDownTimer } = this.data
    countDownTimer = setInterval(() => {
      countDownTime--
      if (countDownTime == 0) {
        // 倒计时以结束
        // 清除定时器，重置倒计时状态
        this.setData({
          countDownTime: 0,
          countDownTimeTotal: 0,
          countDownState: 3
        })
        clearInterval(countDownTimer)
        return
      }

      // 设置定时器状态
      countDownState = 1
      this.setData({
        countDownTime,
        countDownState
      })
    }, 1000)
    this.setData({
      countDownTimer
    })
  },


  // 展示选择事件弹窗
  showSelectTimePicker() {
    this.setData({
      isShowTimePicker: true
    })
  },

  // 关闭选择时间弹窗
  handleClosePicker() {
    this.setData({
      isShowTimePicker: false
    })
  },

  // 用户选择时间
  selectTime(event) {
    // 计算所需秒数
    let time = event.detail
    let hour = parseInt(time.split(':')[0])
    let minute = parseInt(time.split(":")[1])
    let second = hour * 60 * 60 + minute * 60
    this.setData({
      countDownTime: second,
      countDownTimeTotal: second,
      timePickerTime: second,
      currentDate: time,
      isShowTimePicker: false
    });
  },


  // 结束专注，提交云函数
  // flag 是否提前结束
  addFocusItem(flag) {
    let { countDownTitle, timePickerTime, countDownTime, countDownTimeTotal } = this.data
    let time
    if (flag) {
      time = countDownTimeTotal - countDownTime
    } else {
      time = timePickerTime
    }
    let submitObj = {
      title: countDownTitle,
      time,
      date:new Date().toJSON()
    }

    wx.showLoading({
      title: '请稍等',
      mask: true
    })
    // 调用云函数进行添加
    wx.cloud.callFunction({
      name: 'addFocus',
      data: { ...submitObj },
      success: res => {
        // this.initAllData()
        // 重新获取数据
        this.queryAllFocus()
        wx.hideLoading({
          complete: (res) => { },
        })
        // toast 提示
        wx.showToast({
          title: '休息一下吧!',
          mask: true
        })
      },
      error: err => {
        wx.showToast({
          title: '错误',
          mask: true
        })
      }
    })
  },



  // 查询所有的专注列表
  queryAllFocus(){
    wx.cloud.callFunction({
      name: 'queryAllFocus',
      success:res=>{
        let allFocus = res.result.data
        // 分类出今日的专注
        let todayFocusList = []
        let otherFocusList = []
        allFocus.forEach(item=>{
          // 判断是否为当天
          if(new Date(item.date).setHours(0,0,0,0) == new Date().setHours(0,0,0,0)){
            todayFocusList.push(item)
          }else{
            otherFocusList.push(item)
          }
        })

        this.setData({
          todayFocusList,otherFocusList
        })
      }
    })
  }
})